package com.negative.logic;

import java.util.ArrayList;

import com.negative.activities.NegativeApplication;
import com.negative.activities.R;
import com.negative.data.EventListEntry;
import com.negative.data.Item;
import com.negative.data.SectionItem;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class EventListEntryAdapter extends ArrayAdapter<Item> {

	private Context context;
	private ArrayList<Item> items;
	private LayoutInflater vi;

	public EventListEntryAdapter(Context context, ArrayList<Item> items) {
		super(context, 0, items);
		this.context = context;
		this.items = items;
		vi = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;

		final Item i = items.get(position);
		if (i != null) {
			if (i.isSection()) {
				SectionItem si = (SectionItem) i;
				v = vi.inflate(R.layout.list_item_section, null);

				v.setOnClickListener(null);
				v.setOnLongClickListener(null);
				v.setLongClickable(false);

				final TextView sectionView = (TextView) v
						.findViewById(R.id.list_item_section_text);
				sectionView.setText(si.getTitle());
				sectionView.setBackgroundColor(Color.parseColor("#6699FF"));
			} else {
				final EventListEntry ei = (EventListEntry) i;
				v = vi.inflate(R.layout.eventlist_entry, null);
				final ImageView pic = (ImageView) v
						.findViewById(R.id.event_pic);
				final TextView title = (TextView) v
						.findViewById(R.id.eticket_event_name);
				final TextView subtitle = (TextView) v
						.findViewById(R.id.event_time);

				v.setId(i.getIndex());
				if (title != null)
					title.setText(ei.name);
				if (subtitle != null)
					subtitle.setText(ei.time);
				if (pic != null && ei.picURL != null && !ei.picURL.isEmpty()) {
					Thread t = new Thread() {
						public void run() {
							final Bitmap icon = ((NegativeApplication)context.getApplicationContext()).getEventPic(ei.picURL);
							((Activity)context).runOnUiThread(new Runnable() {
								public void run() {
									pic.setImageBitmap(icon);
									}
								});
							}
					};
					t.start();
				}
			}
		}
		return v;
	}
}